package com.nanyang.tms.manager.forecast.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.nanyang.common.core.annotation.SystemLog;
import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.common.core.domain.ApiResult;
import com.nanyang.common.core.page.PageBean;
import com.nanyang.common.core.page.PageTableBean;
import com.nanyang.common.third.bos.entity.ObsRequestEntity;
import com.nanyang.common.third.bos.util.HwObsUtil;
import com.nanyang.common.tool.utils.convert.BeanUtils;
import com.nanyang.common.tool.utils.uuid.GlobalIdGeneratorUtil;
import com.nanyang.common.tool.utils.uuid.UUIDUtil;
import com.nanyang.sys.api.service.tag.TagTemplateRpcService;
import com.nanyang.sys.common.contstant.SysCommonConsts;
import com.nanyang.sys.common.dict.LogExceptionEnum;
import com.nanyang.tms.common.config.HwObsConfig;
import com.nanyang.tms.common.contstant.TmsCommonConsts;
import com.nanyang.tms.common.contstant.TmsSerializeConstant;
import com.nanyang.tms.common.dict.TmsCommonEnum;
import com.nanyang.tms.common.dict.TmsExceptionEnum;
import com.nanyang.tms.common.exception.TmsManagerException;
import com.nanyang.tms.common.util.PdfUtils;
import com.nanyang.tms.common.util.RpcCheckUtils;
import com.nanyang.tms.common.util.TmsExceptionUtil;
import com.nanyang.tms.dao.company.CompanyDao;
import com.nanyang.tms.dao.company.CompanyStoredDao;
import com.nanyang.tms.dao.company.CompanyTransactionRecordDao;
import com.nanyang.tms.dao.forecast.*;
import com.nanyang.tms.dao.product.ProductRuleDao;
import com.nanyang.tms.dao.ticket.TicketRecordDao;
import com.nanyang.tms.domain.company.CompanyStoredDO;
import com.nanyang.tms.domain.company.CompanyStoredVO;
import com.nanyang.tms.domain.company.CompanyTransactionRecordDO;
import com.nanyang.tms.domain.forecast.*;
import com.nanyang.tms.domain.product.ProductRuleVO;
import com.nanyang.tms.domain.ticket.TicketRecordDO;
import com.nanyang.tms.domain.ticket.TicketRecordVO;
import com.nanyang.tms.manager.forecast.ForecastManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component("forecastManager")
public class ForecastManagerImpl implements ForecastManager{
	@Autowired
	private ForecastDao forecastDao;
	@Autowired
	private TicketRecordDao ticketRecordDao;
	@Autowired
	private ForecastVolumeDao forecastVolumeDao;
	@Autowired
	private TransactionTemplate transactionTemplate;
	@Autowired
	private ForecastSenderDao forecastSenderDao;
	@Autowired
	private ForecastReceiverDao forecastReceiverDao;
	@Autowired
	private ForecastDeclareDao forecastDeclareDao;
    @Autowired
    private CompanyStoredDao companyStoredDao;
    @Autowired
    private CompanyTransactionRecordDao companyTransactionRecordDao;
    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ProductRuleDao productRuleDao;
    @Reference(version = "1.0.0", timeout = 10000, check = false)
    private TagTemplateRpcService tagTemplateRpcService;
    @Autowired
    private HwObsConfig hwObsConfig;
	@Override
	public void updateTicketNo(String forecastCode, String ticketTypeCode) {
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult(){
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				try {
					TicketRecordVO queryTicketRecord = ticketRecordDao.queryTicketRecord(ticketTypeCode);
					if(queryTicketRecord==null){
						throw new TmsManagerException(TmsExceptionEnum.TICKET_NO_IS_NOT_EXIST.getCode(), TmsExceptionEnum.TICKET_NO_IS_NOT_EXIST.getMessage());
					}
					ForecastDO forecastDO=new ForecastDO();
					forecastDO.setForecastCode(forecastCode);
					forecastDO.setSupplierNo(queryTicketRecord.getTicketNo());
					forecastDao.update(forecastDO);
					
					List<ForecastVolumeVO> listForecastVolume = forecastVolumeDao.listForecastVolume(forecastCode);
					for(int i=0;i<listForecastVolume.size();i++){
						StringBuffer  supplierSubNo=new StringBuffer(queryTicketRecord.getTicketNo());
						if(listForecastVolume.size()>1){
							supplierSubNo.append("-").append(i+1);
						}
						ForecastVolumeDO forecastVolumeDO=new ForecastVolumeDO();
						forecastVolumeDO.setForecastCode(forecastCode);
						forecastVolumeDO.setVolumeCode(listForecastVolume.get(i).getVolumeCode());
						forecastVolumeDO.setSupplierSubNo(supplierSubNo.toString());
						forecastVolumeDao.update(forecastVolumeDO);
					}
					TicketRecordDO record =new TicketRecordDO();
					record.setId(queryTicketRecord.getId());
					record.setState(1);
					ticketRecordDao.update(record);
				} catch (Exception e) {
					status.setRollbackOnly();
					throw TmsExceptionUtil.wrapException(e);
				}
				
				
	
			}
			
		});
		

		
	}
	
    @Override
    public PageBean<ForecastVO> listForecast(ForecastQuery query) {
        try {
            if (query == null) {
                log.error(TmsCommonEnum.PARAM_IS_NULL.getCode() + TmsCommonEnum.PARAM_IS_NULL.getMessage());
                throw new TmsManagerException(TmsCommonEnum.PARAM_IS_NULL.getCode() ,TmsCommonEnum.PARAM_IS_NULL.getMessage());
            }
            Integer count = forecastDao.countForecast(query);
            PageBean<ForecastVO> page = new PageTableBean<ForecastVO>(query.getPageIndex(), query.getPageSize());
            if (null != count && count != 0) {
                page.setTotalItem(count);
                int startRow = page.getStartRow();
                if (startRow > 0) {
                    startRow -= 1;
                }
                query.setStartRow(startRow);
                page.addAll(forecastDao.listForecast(query));
            }
            return page;
        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }

    @Override
    public ForecastBaseVO selectByCode(String forecastCode){
        try {
            ForecastBaseVO forecastBaseVO = new ForecastBaseVO();

            ForecastVO forecastVO = forecastDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastVO(forecastVO);

            ForecastSenderVO forecastSenderVO = forecastSenderDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastSenderVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastSenderVO(forecastSenderVO);

            ForecastReceiverVO forecastReceiverVO = forecastReceiverDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastReceiverVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastReceiverVO(forecastReceiverVO);

            List<ForecastDeclareVO> forecastDeclareVOS = forecastDeclareDao.selectByCode(forecastCode);
            if(CollectionUtil.isEmpty(forecastDeclareVOS)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastDeclareVOList(forecastDeclareVOS);

            List<ForecastVolumeVO> forecastVolumeVOS = forecastVolumeDao.selectByCode(forecastCode);
            if(CollectionUtil.isEmpty(forecastVolumeVOS)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastVolumeVOList(forecastVolumeVOS);
            return forecastBaseVO;
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }

	@Override
	public ForecastDetailVO getForecastDetail(String ticketNo) {
		try {
			ForecastDetailVO forecastDetail = forecastDao.getForecastDetail(ticketNo);
	        List<ForecastDetailVolumeVO> listForecastVolumeBy = forecastDao.listForecastVolumeBy(ticketNo);
	        if(ObjectUtils.isEmpty(forecastDetail)||CollectionUtil.isEmpty(listForecastVolumeBy)){
	    	   throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
	        }
	        forecastDetail.setVolumes(listForecastVolumeBy);
			return forecastDetail;
		} catch (Exception e) {
			throw TmsExceptionUtil.wrapException(e);
		}

	}


    @Override
    public ForecastBaseVO selectByCompanyCode(ForecastQuery query){
        try {
            ForecastBaseVO forecastBaseVO = new ForecastBaseVO();
            ForecastVO forecastVO = forecastDao.selectByCompanyCode(query);
            if(Objects.isNull(forecastVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            String forecastCode=query.getForecastCode();
            forecastBaseVO.setForecastVO(forecastVO);

            ForecastSenderVO forecastSenderVO = forecastSenderDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastSenderVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastSenderVO(forecastSenderVO);

            ForecastReceiverVO forecastReceiverVO = forecastReceiverDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastReceiverVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastReceiverVO(forecastReceiverVO);

            List<ForecastDeclareVO> forecastDeclareVOS = forecastDeclareDao.selectByCode(forecastCode);
            if(CollectionUtil.isEmpty(forecastDeclareVOS)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastDeclareVOList(forecastDeclareVOS);

            List<ForecastVolumeVO> forecastVolumeVOS = forecastVolumeDao.selectByCode(forecastCode);
            if(CollectionUtil.isEmpty(forecastVolumeVOS)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            forecastBaseVO.setForecastVolumeVOList(forecastVolumeVOS);
            return forecastBaseVO;
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }
    @SystemLog(module =SystemLog.Module.FORCECAST,template="forecastCancel")
    @Override
    @Transactional
    public void cancelState(ForecastDO forecastDO){
        try {
            ForecastVO forecastVO = forecastDao.selectByCode(forecastDO.getForecastCode());
            if(Objects.isNull(forecastVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            if(forecastDao.cancelState(forecastDO)<=0){
                throw new TmsManagerException(TmsExceptionEnum.FORECAST_CANCEL_ERROR.getCode() ,TmsExceptionEnum.FORECAST_CANCEL_ERROR.getMessage());
            }

            CompanyStoredDO companyStoredDO=new CompanyStoredDO();
            companyStoredDO.setFrozenAmount(forecastVO.getAmount());
            companyStoredDO.setGmtModifiedPin(forecastDO.getGmtModifiedPin());
            companyStoredDO.setCompanyCode(forecastDO.getCompanyCode());
            if(companyStoredDao.cancelFrozenAmount(companyStoredDO)<=0){
                throw new TmsManagerException(TmsExceptionEnum.FORECAST_CANCEL_AMOUNT_ERROR.getCode(), TmsExceptionEnum.FORECAST_CANCEL_AMOUNT_ERROR.getMessage());
            }
            CompanyStoredVO companyStored = companyStoredDao.getCompanyStored(forecastDO.getCompanyCode());
            if(companyStored == null){
                throw new TmsManagerException(TmsExceptionEnum.COMPANY_STORE_IS_NOT_EXIST.getCode(), TmsExceptionEnum.COMPANY_STORE_IS_NOT_EXIST.getMessage());
            }
            CompanyTransactionRecordDO companyTransactionRecordDO=new CompanyTransactionRecordDO();
            String recordCode= TmsSerializeConstant.COMPANYADTRANSACTION_KEY+globalIdGeneratorUtil.getNextSeq(TmsSerializeConstant.COMPANYADTRANSACTION_SEQ_KEY, TmsSerializeConstant.SEQ_INCRBY);
            companyTransactionRecordDO.setRecordCode(recordCode);
            companyTransactionRecordDO.setBillTypeCode("FROZEN");
            companyTransactionRecordDO.setBillTypeName("冻结");
            companyTransactionRecordDO.setBillCode(forecastVO.getForecastCode());
            companyTransactionRecordDO.setCardNo(companyStored.getCardNo());
            companyTransactionRecordDO.setCardName(companyStored.getCardName());
            companyTransactionRecordDO.setAmountType(0);
            companyTransactionRecordDO.setAmount(forecastVO.getAmount());
            companyTransactionRecordDO.setActualBalance(companyStored.getActualBalance());
            companyTransactionRecordDO.setUseBalance(companyStored.getUseBalance());
            companyTransactionRecordDO.setFrozenAmount(companyStored.getFrozenAmount());
            companyTransactionRecordDO.setPin(companyStored.getPin());
            companyTransactionRecordDO.setUserName(companyStored.getUserName());
            companyTransactionRecordDO.setCompanyCode(companyStored.getCompanyCode());
            companyTransactionRecordDO.setCompanyName(companyDao.selectByCode(companyStored.getCompanyCode()).getCompanyName());
            companyTransactionRecordDO.setIp(companyStored.getIp());
            companyTransactionRecordDO.setGmtCreatePin(companyStored.getPin());
            companyTransactionRecordDao.insert(companyTransactionRecordDO);//添加交易明细
        } catch (TmsManagerException e) {
            throw TmsExceptionUtil.wrapException(e);
        }
    }
    @SystemLog(module =SystemLog.Module.FORCECAST,template="forecastPrintTag")
    @Override
    @Transactional
    public String printTag(ForecastQuery query){
        try {
            List<String> files=new ArrayList<>();
            ObsRequestEntity entity = new ObsRequestEntity();
            BeanUtils.copyProperties(hwObsConfig, entity);
            query.getForecastCodeList().forEach(str ->{
                query.setForecastCode(str);
                ForecastVO forecastVO = forecastDao.selectByCompanyCode(query);
                if(Objects.isNull(forecastVO)){
                    throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
                }
                ProductRuleVO productRule = productRuleDao.getProductRule(forecastVO.getSaleProductCode());
                if(Objects.isNull(productRule)|| StringUtils.isEmpty(productRule.getTagCode())){
                    throw new TmsManagerException(TmsExceptionEnum.TEMP_CODE_ERROR.getCode(),TmsExceptionEnum.TEMP_CODE_ERROR.getMessage());
                }
                ApiResult<String> tagTemplateUrl = tagTemplateRpcService.getTagTemplateUrl(productRule.getTagCode());
                if(RpcCheckUtils.isRpcInvokeError(tagTemplateUrl)){
                    log.error("查询标签模板信息失败：入参{},返回{}", productRule.getTagCode(), JSONUtil.toJsonStr(tagTemplateUrl));
                    throw new TmsManagerException(TmsExceptionEnum.TEMP_SELECT_ERROR.getCode(),TmsExceptionEnum.TEMP_SELECT_ERROR.getMessage());
                }
                ForecastDO forecastDO=new ForecastDO();
                forecastDO.setForecastCode(query.getForecastCode());
                forecastDO.setCompanyCode(query.getCompanyCode());
                forecastDao.updatePrint(forecastDO);
                //判断obs上是否存在文件
                entity.setBucketName(hwObsConfig.getBucketName());
                String uploadPath=hwObsConfig.getUploadFilePath()+str+".pdf";
                boolean hasObsFile = HwObsUtil.hasObsFile(entity, uploadPath);
                if(hasObsFile){
                    files.add(TmsCommonConsts.LEFT_SLASH +hwObsConfig.getBucketName()+TmsCommonConsts.LEFT_SLASH +uploadPath) ;
                }
            });

            if(CollectionUtil.isNotEmpty(files)){
                List<String> localList=new ArrayList<>();
                String mergePath=hwObsConfig.getLocalFilePath()+ UUIDUtil.uuid()+".pdf";
                for (String file : files) {
                    String localPath=hwObsConfig.getLocalFilePath()+ HwObsUtil.getObsFileName(file);
                    HwObsUtil.getResourceFile(entity,file,localPath);
                    localList.add(localPath);
                }
                PdfUtils.mergePdf(localList,mergePath);
                // 上传文件到OBS服务器
                String uploadPath=hwObsConfig.getUploadFilePath()+UUIDUtil.uuid()+".pdf";
                File localFile = new File(mergePath);
                entity.setBucketName(hwObsConfig.getBucketName());
                String fileUrl = HwObsUtil.createFile(entity, uploadPath,localFile , true);
                FileUtil.del(localFile);
                if (StringUtils.isBlank(fileUrl)) {
                    throw new TmsManagerException(LogExceptionEnum.HWOBS_UPLOAD_FAIL.getCode(),LogExceptionEnum.HWOBS_UPLOAD_FAIL.getMessage());
                }
                return fileUrl;
            }else{
                throw new TmsManagerException(TmsExceptionEnum.GET_PRINT_TAG_ERROR.getCode(),TmsExceptionEnum.GET_PRINT_TAG_ERROR.getMessage());
            }

        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }

    }

    @Override
    @Transactional
    public void syncPrintTag(String  forecastCode){
        try {
            ForecastBaseVO forecastBaseVO = selectByCode(forecastCode);
            if(Objects.isNull(forecastBaseVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            ProductRuleVO productRule = productRuleDao.getProductRule(forecastBaseVO.getForecastVO().getSaleProductCode());
            if(Objects.isNull(productRule)|| StringUtils.isEmpty(productRule.getTagCode())){
                throw new TmsManagerException(TmsExceptionEnum.TEMP_CODE_ERROR.getCode(),TmsExceptionEnum.TEMP_CODE_ERROR.getMessage());
            }
            ApiResult<String> tagTemplateUrl = tagTemplateRpcService.getTagTemplateUrl(productRule.getTagCode());
            if(RpcCheckUtils.isRpcInvokeError(tagTemplateUrl)){
                log.error("查询标签模板信息失败：入参{},返回{}", productRule.getTagCode(), JSONUtil.toJsonStr(tagTemplateUrl));
                throw new TmsManagerException(TmsExceptionEnum.TEMP_SELECT_ERROR.getCode(),TmsExceptionEnum.TEMP_SELECT_ERROR.getMessage());
            }
            ObsRequestEntity entity = new ObsRequestEntity();
            BeanUtils.copyProperties(hwObsConfig, entity);
            entity.setBucketName(hwObsConfig.getSysBucketName());
            String filePath = tagTemplateUrl.getData();
            String templateUrl=hwObsConfig.getLocalFilePath()+ HwObsUtil.getObsFileName(filePath);
            HwObsUtil.getResourceFile(entity,filePath , templateUrl);
            long startJobTs = System.currentTimeMillis();
            String sfile = PdfUtils.tagPrint(templateUrl, hwObsConfig.getLocalFilePath(), BeanUtil.beanToMap(forecastBaseVO));
            log.info("生成pdf耗时:" + (System.currentTimeMillis() - startJobTs) + "ms");
            // 上传文件到OBS服务器
            long startJobTs1 = System.currentTimeMillis();
            File localFile = new File(sfile);
            String uploadPath=hwObsConfig.getUploadFilePath()+forecastCode+".pdf";
            entity.setBucketName(hwObsConfig.getBucketName());
            String fileUrl = HwObsUtil.createFile(entity, uploadPath,localFile , true);
            FileUtil.del(localFile);
            if (StringUtils.isBlank(fileUrl)) {
                throw new TmsManagerException(LogExceptionEnum.HWOBS_UPLOAD_FAIL.getCode(),LogExceptionEnum.HWOBS_UPLOAD_FAIL.getMessage());
            }
            log.info("上传obs总耗时:" + (System.currentTimeMillis() - startJobTs1) + "ms");

            syncPrintList(forecastCode);
        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }

    }


    public String syncPrintList(String  forecastCode){
        try {
            ForecastVO forecastVO = forecastDao.selectByCode(forecastCode);
            if(Objects.isNull(forecastVO)){
                throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
            }
            ObsRequestEntity entity = new ObsRequestEntity();
            BeanUtils.copyProperties(hwObsConfig, entity);
            String filePath=hwObsConfig.getDetailListPath();
            String templateUrl=hwObsConfig.getLocalFilePath()+ HwObsUtil.getObsFileName(filePath);
            HwObsUtil.getResourceFile(entity,filePath , templateUrl);
            String sfile = PdfUtils.printList(templateUrl, hwObsConfig.getLocalFilePath(), BeanUtil.beanToMap(forecastVO));
            // 上传文件到OBS服务器
            File localFile = new File(sfile);
            String uploadPath=hwObsConfig.getUploadFilePath()+"DL_"+forecastCode+".pdf";
            String fileUrl = HwObsUtil.createFile(entity, uploadPath,localFile , true);
            FileUtil.del(localFile);
            if (StringUtils.isBlank(fileUrl)) {
                throw new TmsManagerException(LogExceptionEnum.HWOBS_UPLOAD_FAIL.getCode(),LogExceptionEnum.HWOBS_UPLOAD_FAIL.getMessage());
            }
            return fileUrl;
        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }

    }
    @SystemLog(module =SystemLog.Module.FORCECAST,template="forecastPrintList")
    @Override
    public String printList(ForecastQuery query){
        try {
            List<String> files=new ArrayList<>();
            ObsRequestEntity entity = new ObsRequestEntity();
            BeanUtils.copyProperties(hwObsConfig, entity);
            query.getForecastCodeList().forEach(str ->{
                query.setForecastCode(str);
                ForecastVO forecastVO = forecastDao.selectByCompanyCode(query);
                if(Objects.isNull(forecastVO)){
                    throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
                }
                String uploadPath=hwObsConfig.getUploadFilePath()+"DL_"+str+".pdf";
                boolean hasObsFile = HwObsUtil.hasObsFile(entity, uploadPath);
                if(hasObsFile){
                    files.add(TmsCommonConsts.LEFT_SLASH +hwObsConfig.getBucketName()+TmsCommonConsts.LEFT_SLASH +uploadPath);
                }
            });
            if(CollectionUtil.isNotEmpty(files)){
                List<String> localList=new ArrayList<>();
                String mergePath=hwObsConfig.getLocalFilePath()+ UUIDUtil.uuid()+".pdf";
                for (String file : files) {
                    String localPath=hwObsConfig.getLocalFilePath()+ HwObsUtil.getObsFileName(file);
                    HwObsUtil.getResourceFile(entity,file,localPath);
                    localList.add(localPath);
                }
                PdfUtils.mergePdf(localList,mergePath);
                // 上传文件到OBS服务器
                String uploadPath=hwObsConfig.getUploadFilePath()+UUIDUtil.uuid()+".pdf";
                File localFile = new File(mergePath);
                entity.setBucketName(hwObsConfig.getBucketName());
                String fileUrl = HwObsUtil.createFile(entity, uploadPath,localFile , true);
                FileUtil.del(localFile);
                if (StringUtils.isBlank(fileUrl)) {
                    throw new TmsManagerException(LogExceptionEnum.HWOBS_UPLOAD_FAIL.getCode(),LogExceptionEnum.HWOBS_UPLOAD_FAIL.getMessage());
                }
                return fileUrl;
            }else{
                throw new TmsManagerException(TmsExceptionEnum.GET_PRINT_LIST_ERROR.getCode(),TmsExceptionEnum.GET_PRINT_LIST_ERROR.getMessage());
            }
        } catch (Exception e) {
            throw TmsExceptionUtil.wrapException(e);
        }

    }
}
